<template>
  <div class="image-displayer" :class="`flex-${numPerRow}`">
    <div class="image-wrapper" v-for="imagePath in imagePathList" :key="imagePath">
      <img
        :src="imagePath"
        class="image"
        @mousedown="moved=false"
        @mousemove="moved=true"
        @mouseup="!moved?$emit('requestDisplayImage',imagePath):''"
        @touchstart="moved=false"
        @touchmove="moved=true"
        @touchend="!moved?$emit('requestDisplayImage',imagePath):''"
      /></div>
    <div class="empty" v-for="item in emptyElementNum"/>
  </div>
</template>
<script>
  export default {
    props: {
      imagePathList: {
        type: Array,
        default() {
          return []
        }
      }
    },
    data() {
      return {
//        兼容手机touch事件
        moved :true
      }
    },
    computed: {
//      需要展示的图片数量
      imageNum() {
        return this.imagePathList.length
      },
      numPerRow() {
//        计算每行排多少张图片/
        if ([3, 5, 6, 7, 8, 9].includes(this.imageNum)) {
          return 3
        }
        if ([2, 4].includes(this.imageNum)) {
          return 2
        }
        return 1
      },
      emptyElementNum() {
        return (this.numPerRow - this.imageNum % this.numPerRow) % this.numPerRow
      }
    },


    watch: {
      imageNum(value) {
        if (value > 9) {
//          暂时限制为9张图片
          throw new Error('传入图片数量不得超过9张!')
        }
      }
    },
    methods:{
      requestDisplayImage(src){
        console.log('OK')
      },
      test(){
        console.log('test')

      }
    }
  }
</script>
<style scoped>
  .image-displayer {
    display: flex;
    flex-wrap: wrap;
    width: 100%;
  }

  .image-wrapper {
    overflow: hidden;
    position: relative;
  }
  .flex-1 .image-wrapper, .flex-1 .empty {
    width: 100%;
    height: 0;
    padding-bottom: 100%;
  }

  .flex-2 .image-wrapper, .flex-2 .empty {
    width: 50%;
    height: 0;
    padding-bottom: 50%;
  }

  .flex-3 .image-wrapper, .flex-3 .empty {
    width: 33.33%;
    height: 0;
    padding-bottom: 33.33%;
  }

  .image {
    position: absolute;
    left: 0;
    top: 0;
    object-fit: cover;
    width: 100%;
    height: 100%;
  }
</style>
